<template>
  <el-drawer
      title="我是标题"
      :with-header="false"
      :visible.sync="visible"
      :direction="direction"
      custom-class="layer_wrap drawer_source"
      :before-close="() => handleCancel()">
    <div class="layer_inside">
      <div class="layer_header">
        <span class="title">选择素材</span>
      </div>
      <div class="layer_content">
        <div class="screen-area">
          <el-form :model="queryParams" ref="queryFormRef" :inline="true">
            <el-form-item label="素材类型" prop="classification">
              <el-select v-model="queryParams.classification" placeholder="请选择" clearable :disabled="!!(info?.type)">
                <el-option
                    v-for="dict in sourceOption"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">检索</el-button>
              <el-button icon="Refresh" @click="handleReset">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="content-area flex-box">
          <div class="left flex-box-left">
            <el-table
                border
                height="400"
                ref="elTable"
                v-loading="loading"
                :data="sourceInfo.rows"
                class="table-area"
                @selection-change="handleRow"
                :row-key="(row) => row.id"
            >
              <el-table-column type="selection" :reserve-selection="true"/>
              <el-table-column prop="name" label="素材名称">
                <template v-slot="scope">
                  <div class="item name-inside" slot="reference"> {{ (scope.row.name) }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="address" label="素材类型">
                <template v-slot="scope">
                  <div>{{ scope.row.type }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="创建时间">
                <template v-slot="scope">
                  <div class="item">{{ scope.row.createTime }}</div>
                </template>
              </el-table-column>
              <el-table-column label="预览" v-if="false">
                <template v-slot="scope">
                  <el-row class="operator-box">
                    <el-col :push="8" :span="8" class="edit item" title="预览">
                      <div class="image_preview">
                        <el-image
                            lazy
                            ref="previewImg"
                            :src="`${scope.row.url}?t=${getOnlyId()}`"
                            :preview-src-list="[`${scope.row.url}?t=${getOnlyId()}`]"
                        />
                      </div>
                    </el-col>
                  </el-row>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination-box" v-if="sourceInfo?.rows?.length">
              <Pagination :pageInfo="sourceInfo" @handleChangePage="handleChangePage"/>
            </div>
          </div>
          <div class="right flex-box-right">
            <el-table
                border
                height="400"
                ref="active_table"
                :data="checkedInfo"
                class="table-area"
            >
              <el-table-column prop="name" label="素材名称">
                <template v-slot="scope">
                  <div class="item name-inside" slot="reference" :data-id="scope.row.id"> {{ (scope.row.name) }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="address" label="素材类型">
                <template v-slot="scope">
                  <div class="item">{{ scope.row.type }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="创建时间">
                <template v-slot="scope">
                  <div>{{ scope.row.createTime }}</div>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template v-slot="scope">
                  <div class="delete" @click="handleDelete(scope.$index,scope.row)">删除</div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <div class="footer-area">
        <div class="inside-item">
          <el-button type="primary" icon="Search" @click="handleSure">确定</el-button>
          <el-button icon="Refresh" @click="handleCancel">取消</el-button>
        </div>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import {v4 as uuid} from "uuid";
import {ModelDesignApi} from "@/api/modeldesign";
import Pagination from "@c/public/pagination/index.vue";
import * as types from "@c/public/form-designer/devType/datas-types";

export default {
  name: 'DrawerSource',
  components: {Pagination},

  props: {
    info: {
      type: Object,
      required: true
    },
    visible: {
      type: Boolean,
      required: true,
      default: false
    },
  },

  data() {
    return {
      loading: false,
      direction: 'rtl',
      sourceInfo: Object(),
      queryParams: {
        name: '',
        classification: '',
        deptIds: Array(),
        pageNum: 1,
        pageSize: 10,
      },
      checkedInfo: Array(),
      sourceOption: types['sourceOption']
    }
  },

  computed: {
    //生成唯一的字符串
    getOnlyId() {
      return function () {
        return uuid()
      }
    },
  },

  mounted() {
  },

  methods: {
    // 关闭
    handleCancel() {
      self.loading = false;
      this.$emit('handleCancel');
    },

    // 确定
    handleSure() {
      let params = Object();
      let {updataType} = this.info;
      Reflect.set(params, 'key', updataType);
      Reflect.set(params, 'val', (this.checkedInfo))
      this.$emit('handleSure', params);
      this.handleCancel();
    },

    // 筛选
    handleQuery() {
      this.sourceListInfo();
    },

    // 重置
    handleReset() {
      const self = this;
      Reflect.set(self.queryParams, 'pageNum', 1);
      Reflect.set(self.queryParams, 'pageNum', 20);
      Reflect.set(self.queryParams, 'classification', '');
      self.sourceListInfo();
    },

    // 分页
    handleChangePage(val) {
      const self = this;
      Reflect.set(self.queryParams, 'pageNum', val);
      self.sourceListInfo();
    },

    // 选择对应元素
    handleRow(row) {
      const self = this;
      let tempMap = new Map();
      row.forEach((item) => {
        tempMap.set(item.id, item);
      });
      self.sourceInfo?.rows.forEach((item) => {
        const result = self.checkedInfo.findIndex((row) => row.id === item.id);
        if (tempMap.get(item.id)) {
          if (result < 0) {
            this.checkedInfo.push(item);
          }
        } else {
          if (result >= 0) {
            self.checkedInfo.splice(result, 1);
          }
        }
      });
    },

    //   查询资源列表
    async sourceListInfo() {
      const self = this;
      try {
        self.loading = true;
        const resp = await ModelDesignApi.getMaterial(self.queryParams);
        if (resp && (resp.code) === 200) {
          self.sourceInfo = (resp.data);
          self.$nextTick(() => {
            let rows = (self.info?.content) || Array();
            let rowId = self.$lodash.map(rows, 'id');
            // 选中的对象
            let checkedInfo = self.$lodash.filter((resp?.data?.rows || Array()), function (items) {
              return rowId.includes(items.id);
            });
            self.handleToggleSelection(checkedInfo, 'elTable')
          })

        }
      } catch (e) {
        console.log(e)
      } finally {
        self.loading = false;
      }
    },


    // 回显选中的数据
    handleToggleSelection(rows, el) {
      const self = this;
      if (rows?.length) {
        rows.forEach((item) => {
          // 切换选中状态
          self.$refs[el].toggleRowSelection(item, true)
        })
      } else {
        // 清空选中
        this.$refs[el].clearSelection()
      }
    },

    // 移除选中的元素
    async handleDelete(index, row) {
      const self = this;
      this.checkedInfo.splice(index, 1);
      const indexNum = self.sourceInfo.rows.findIndex((item) => item.id === row.id);
      if (indexNum >= 0) {
        this.$refs['elTable'].toggleRowSelection(self.sourceInfo.rows[indexNum], false);
      }
    },
  },

  watch: {
    async visible(val) {
      const self = this;
      let {content,type,multiple,updataType} = self.info;
      if (val) {
        self.widgetKey = uuid();
        Reflect.set(self.queryParams, 'pageNum', 1)
        Reflect.set(self.queryParams, 'pageSize', 20);
        Reflect.set((self.queryParams),'classification',type);
        self.checkedInfo = [...content];
        await self.sourceListInfo();
      }
    }
  }
}

</script>

<style lang="scss" scoped>
@import "assets/style";
</style>